package com.wekri.wechat4j.token;

import com.alibaba.fastjson.JSONObject;
import com.wekri.wechat4j.BaseMsg;
import com.wekri.wechat4j.util.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * @author liuweiguo.
 */
public class AccessToken extends BaseMsg {

    private static Logger logger = LoggerFactory.getLogger(AccessToken.class);
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    private String appid;
    private String appsecret;

    private String access_token;
    private Long expires_in;

    public AccessToken(String appid, String appsecret) {
        this.appid = appid;
        this.appsecret = appsecret;
    }

    public String getAccess_token() {
        return access_token;
    }

    public void setAccess_token(String access_token) {
        this.access_token = access_token;
    }

    public Long getExpires_in() {
        return expires_in;
    }

    public void setExpires_in(Long expires_in) {
        this.expires_in = expires_in;
    }

    public boolean request(){
        String url = accessTokenUrl();
        String result = HttpUtils.get(url);
        if(StringUtils.isBlank(result)){
            return false;
        }
        if(!parseData(result)){
            return false;
        }
        return true;
    }

    /**
     * 解析token数据
     *
     * @param data
     * @return
     */
    private boolean parseData(String data) {
        JSONObject jsonObject = JSONObject.parseObject(data);
        try {
            String token = jsonObject.getString("access_token");
            Long expiresIn = jsonObject.getLong("expires_in");

            if (StringUtils.isBlank(token)) {
                logger.error("token获取失败,获取结果{}", data);
                return false;
            }
            this.access_token = token;

            if (null == expiresIn) {
                logger.error("token获取失败,获取结果:{}", expiresIn);
                return false;
            }
            this.expires_in = (new Date()).getTime() + expiresIn;
        } catch (Exception e) {
            logger.error("token 结果解析失败，token请求结果:{}", data);
            return false;
        }
        return true;
    }


    protected String accessTokenUrl() {
        StringBuilder url = new StringBuilder(ACCESS_TOKEN_URL)
                .append("&appid=").append(appid)
                .append("&secret=").append(appsecret);
        logger.info("创建获取access_token url:{}", ACCESS_TOKEN_URL);
        return url.toString();
    }
}